import React from 'react';
import { connect } from 'dva';
import { Redirect } from 'umi';
import { stringify } from 'querystring';
import { ConnectState, ConnectProps } from '@/models/connect';
import { CurrentUser } from '@/models/user';
import PageLoading from '@/components/PageLoading';
import Cookies from 'js-cookie';
import { MenuItem } from '@/models/menu';

interface SecurityLayoutProps extends ConnectProps {
  loading: boolean;
  currentUser: CurrentUser;
  menuList: Array<MenuItem>;
}

interface SecurityLayoutState {
  isReady: boolean;
  isLogin: boolean;
}

class SecurityLayout extends React.Component<SecurityLayoutProps, SecurityLayoutState> {
  state: SecurityLayoutState = {
    isReady: false,
    isLogin: false,
  };

  async componentDidMount() {
    const { dispatch } = this.props;

    /* 获取登录信息 */
    let user = Cookies.get('user');
    if (user) {
      user = JSON.parse(user);
      if (dispatch) {
        dispatch({
          type: 'user/saveCurrentUser',
          payload: user,
        });
      }
      this.setState({
        isLogin: true,
      });
    } else {
      this.setState({
        isLogin: false,
      });
    }

    /* 获取用户的目录 */
    await this.initMenu(dispatch);
    this.setState({
      isReady: true,
    });
  }

  initMenu = async (dispatch: any) => {
    await dispatch({
      type: 'menus/fetchMenu',
    });
  };

  render() {
    const { isReady, isLogin } = this.state;
    const { children, loading } = this.props;
    // You can replace it to your authentication rule (such as check token exists)
    // 你可以把它替换成你自己的登录认证规则（比如判断 token 是否存在）
    const queryString = stringify({
      redirect: window.location.href,
    });

    if ((!isLogin && loading) || !isReady) {
      return <PageLoading />;
    }
    if (!isLogin) {
      return <Redirect to={`/user/login?${queryString}`}></Redirect>;
    }
    return children;
  }
}

export default connect(({ user, loading, menus }: ConnectState) => ({
  currentUser: user.currentUser,
  loading: loading.models.user,
  menuList: menus.menuList,
}))(SecurityLayout);
